<template>
  <div>
    <Dialog
      title="导出数据"
      v-model="show"
      width="800px"
      :before-close="close"
      @open="openDialog"
    >
      <el-form ref="formDataRef" :model="formData" :rules="rules" label-width="100px">
        <h3 class="collpase-title">条件配置</h3>
        <el-form-item label="文件名称：" prop="insId">
          <span> {{ formData.exportName }} </span>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="time"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-time="defaultTime"
          />
        </el-form-item>

        <el-form-item label="检索数据">
          <el-radio-group v-model="formData.conditionLimit">
            <el-radio :label="1">按搜索条件</el-radio>
            <el-radio :label="0">全量数据</el-radio>
          </el-radio-group>

          <!-- <el-radio-group v-model="formData.radio1">
        <el-radio :label="3" />
        <el-radio :label="4" />
      </el-radio-group> -->
        </el-form-item>

        <el-form-item label="导出数据">
          <el-radio-group v-model="formData.countLimit">
            <el-radio :label="0">全部</el-radio>
            <el-radio :label="1">部分</el-radio>
          </el-radio-group>

          <el-form-item
            label-width="20px"
            prop="remark"
            v-show="formData.countLimit == 1"
          >
            <el-input
              class="ipt-count"
              placeholder="请输入数量"
              v-model="formData.showCount"
            >
            </el-input>
          </el-form-item>
        </el-form-item>

        <h3 class="collpase-title">字段配置</h3>
        <el-form-item prop="remark">
          <el-transfer
            v-model="formData.exportVos"
            :titles="['可选择字段', '已选择字段']"
            :props="{
              key: 'key',
              label: 'value',
            }"
            :data="titleList"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close">取 消</el-button>
          <el-button v-notice-export="{shouldNotice}" type="primary" @click="formValidate" :loading="loading">确 定</el-button>
        </span>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import ExportDataApi from "@/api/exportDataApi";
const props = withDefaults(
  defineProps<{
    showDialog: boolean;
    exportType: string;
    searchData?: object;
    timeKey?: [string, string[]];
    timeField?: string[];
    title?: string;
  }>(),
  {
    searchData: {} as any,
    timeKey: [] as any, // [startTime, endTime]
    timeField: [] as any, // [开始字段, 结束字段]
    title: "文件",
  }
);
const loading = ref(false)
const { exportType, searchData, timeKey, timeField, title } = toRefs(props);
const time = ref("" as any);
const defaultTime = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59),
] as any; // '12:00:00', '08:00:00'
const formDataRef = ref();
const formData = ref({
  exportName: "",
  exportStartTime: "" as any,
  exportEndTime: "" as any,
  showCount: "", // 截取条数 - 单次最高50000
  currentPage: "",
  countLimit: 0, //  是否导出全量 0 全量导出    1 导出条数
  conditionLimit: 1, // 是否按条件查询 0 不按条件查询    1 按条件查询
  beanName: exportType.value,
  exportVos: [],
});
const titleList = ref([]);
const rules = ref([] as any);
const emits = defineEmits(["update:showDialog"]);
const show = computed({
  get() {
    return props.showDialog;
  },
  set(val) {
    return emits("update:showDialog", val);
  },
});

watch(
  time,
  (val) => {
    if (val) {
      formData.value.exportStartTime = new Date(val[0]).getTime();
      formData.value.exportEndTime = new Date(val[1]).getTime();
    } else {
      formData.value.exportStartTime = "";
      formData.value.exportEndTime = "";
    }
  }
);

const getVoParm = async () => {
  let rs: any = await ExportDataApi.getVoParm({ beanName: exportType.value });
  if (rs.code === 200) {
    titleList.value = rs.payload;
    console.log("[ rs.payload-getVoParm ]", rs.payload);
  }
};

const openDialog = () => {
  // 保持内外时间一致
  if (timeKey.value.length && timeField.value.length) {
    time.value = [timeKey.value[0], timeKey.value[1]];
  }
  formData.value.exportName = `${title.value}-${new Date().getTime()}`;
  getVoParm();
};
const shouldNotice = ref(false);
const formValidate = () => {
  shouldNotice.value = false;
  console.log("[ searchData.value ]", searchData.value);
  if(!formData.value.exportVos.length) {
    ElMessage.warning('请配置导出字段')
    return
  }
  formDataRef.value.validate(async (valid: any, fields: any) => {
    if (valid) {
      let params = {
        beanName: formData.value.beanName,
        param: {
          ...formData.value,
          ...searchData.value,
        } as any
      };

      // 保持外部传入的时间和导出组件选择的时间保持一致
      if (timeKey.value.length && timeField.value.length) {
        params.param[timeField[0]] = params.param.exportStartTime;
        params.param[timeField[1]] = params.param.exportEndTime;
      }
      params.param = JSON.stringify(params.param)
      loading.value = true
      let rs: any = await ExportDataApi.setExportData(params);
      if (rs.code === 200) {
        shouldNotice.value = true;
        ElMessage.success("数据已加入导出队列，正在准备执行导出，请勿重复操作！");
        close();
      }
      loading.value = false
    } else {
      console.log("error submit!", fields);
    }
    
  });

};

const close = () => {
  // emits("update:showDialog", false)
  show.value = false;
  nextTick(()=>{
    formData.value = {
      exportName: "",
      exportStartTime: "" as any,
      exportEndTime: "" as any,
      showCount: "", // 截取条数 - 单次最高50000
      currentPage: "",
      countLimit: 0, //  是否导出全量 0 全量导出    1 导出条数
      conditionLimit: 1, // 是否按条件查询 0 不按条件查询    1 按条件查询
      beanName: exportType.value,
      exportVos: [],
    }
  })

};
</script>

<style lang="scss" scoped>
.collpase-title {
  position: relative;
  padding-left: 10px;
  font-size: 16px;
  margin-bottom: 10px;
  &::before {
    content: "";
    display: block;
    width: 3px;
    height: 16px;
    border-radius: 2px;
    background-color: var(--el-color-primary);
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
  }
  span {
    font-size: 13px;
    color: #909399;
    margin-left: 10px;
    font-weight: normal;
  }
}

.ipt-count {
  width: 100px;
}
</style>
